/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Apr 14, 2012  4:58:23 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : apps.promis.in.construction
 * File Name : ReReceiptedAction.java
 * TODO
 */
package apps.promis.in.sales;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import jpa.entitys.promis.common.Company;
import jpa.entitys.promis.common.CostBuildingPhase;
import jpa.entitys.promis.common.CostBuildingPhasePK;
import jpa.entitys.promis.common.CostProject;
import jpa.entitys.promis.common.CostProjectUnit;
import jpa.entitys.promis.common.CostProjectUnitPK;
import jpa.entitys.promis.common.CostProjectZone;
import jpa.entitys.promis.common.CostProjectZonePK;
import jpa.entitys.promis.common.MktPaymentReceiptDetail;
import jpa.entitys.promis.common.MktPaymentReceiptDetailPK;
import jpa.entitys.promis.common.MktReceiptDetail;
import jpa.entitys.promis.common.MktReceiptDetailPK;
import jpa.entitys.promis.common.PermanentReceipt;
import jpa.entitys.promis.common.PermanentReceiptPK;
import jpa.entitys.promis.common.PmsPaymentReceivedDetail;
import jpa.entitys.promis.common.PmsPaymentReceivedDetailPK;
import jpa.entitys.promis.sales.BusinessPartner;
import jpa.entitys.promis.sales.VwSyncMktCustBookCont;
import jpa.entitys.synchro.staging.FiReReceiptInb;
import jpa.service.promis.common.CompanyServices;
import jpa.service.promis.common.CostBuildingPhaseServices;
import jpa.service.promis.common.CostProjectUnitServices;
import jpa.service.promis.common.CostProjectZoneServices;
import jpa.service.promis.common.PermanentReceiptServices;
import jpa.service.promis.common.ProjectServices;
import jpa.service.promis.sales.BusinessPartnerServices;
import jpa.service.promis.sales.VwSyncMktCustBookContServices;
import jpa.service.synchro.staging.FiReReceiptInbservices;
import org.apache.log4j.Logger;
import apps.sessionFactory;
import promis.utility.CommonService;
import promis.utility.Utilitys;
import sap.jco.server.SAPServerInfo;

/**
 * 
 * @author Chatree Siangklom of Administrator
 * Date =Nov 13, 2013 : 2:44:32 PM 
 * CreateBy=Chatree Siangklom
 * 
 * ReReceiptedAction
 * TODO
 */
public class ReReceiptedAction {
		
	private static final Logger log = Logger.getLogger(ReReceiptedAction.class);
	private EntityManager  EmPromis;
	private EntityManager  EmSynchro;	
	private PermanentReceiptServices PermanentReceiptServ;
	private FiReReceiptInbservices FiReReceiptInbserv;
	
	/**
	 * 
	 * Date =Nov 12, 2013 : 11:59:19 AM 
	 * CreateBy=Chatree Siangklom
	 * ReReceiptedAction
	 * TODO
	 * @throws Exception
	 */
	public ReReceiptedAction() throws Exception {
		try{
			
			EmPromis = sessionFactory.CreateEmPromis();
			EmSynchro = sessionFactory.CreateEmSynchro();
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:44:41 PM 
	 * CreateBy=Chatree Siangklom
	 * List<ReReceiptedGroupSearch>
	 * TODO {EXT_REF_NO is Keep SAP Document Number of Receipted}
	 * @param sap_receipted_doc_no
	 * @return
	 * @throws Exception
	 */
	private List<ReReceiptedGroupSearch> groupby(String sap_receipted_doc_no) throws Exception {
		
		String sql = "";
		sql += "  Select EXT_REF_NO, STATUS, INSTANCE_NO  ";
		sql += "  From 	FI_RE_RECEIPT_INB where issync = 'N' ";
		
		if(!CommonService.IsNull(sap_receipted_doc_no))
			sql += " And  EXT_REF_NO = '" + sap_receipted_doc_no + "' ";
		
		sql += "  Group By  EXT_REF_NO, STATUS, INSTANCE_NO "; 
		sql += "  Order By  EXT_REF_NO, STATUS, INSTANCE_NO asc ";
		
		log.info(CommonService.ReplaceStringToTxtDatabase(sql));
		List<Object[]> result = (List<Object[]>)EmSynchro.createNativeQuery(sql).getResultList();
		List<ReReceiptedGroupSearch> lst = new ArrayList<ReReceiptedGroupSearch>();
		if(!CommonService.IsNull(result)){
			for (Object[] resultElement : result) {
				String extRefNo = CommonService.IsNullRString(resultElement[0]);				 
				String status = CommonService.IsNullRString(resultElement[1]);
				String instanceNo = CommonService.IsNullRString(resultElement[2]);
				lst.add(new ReReceiptedGroupSearch(extRefNo, status, instanceNo));
			 }
		}
		return lst;
	}
	
	/**
	 * Not receipt status doc : Z,R,X 
	 * @return
	 */
	private boolean isCanReceipt(String company, String project, String document_number) throws Exception {
		try{
			
			StringBuilder _strQuery = new StringBuilder();			
			_strQuery.append(" Select COMPANY, PROJECT, BUILDING_PHASE_CODE, DOCUMENT_NUMBER, STATUS ");
			_strQuery.append(" from VW_SYNC_SALES_CONTRACT ");
			_strQuery.append(" Where status not in ('Z','X','R') ");
			_strQuery.append(" And company = '"+ company +"' ");
			_strQuery.append(" And project = '"+ project +"' ");
			_strQuery.append(" And document_number = '"+ document_number +"' ");
			_strQuery.append(" group by COMPANY, PROJECT, BUILDING_PHASE_CODE, DOCUMENT_NUMBER, STATUS ");			
			
			List<Object[]> result = (List<Object[]>)EmPromis.createNativeQuery(_strQuery.toString()).getResultList();
			if(CommonService.getSize(result) == 1){
				for (Object[] value : result) {
					String DOCUMENT_NUMBER = value[3].toString();
					
					if(!CommonService.IsNull(DOCUMENT_NUMBER))
						return true;
				}
			}else
				return false;
			
		}catch(Exception e){
			System.out.println(e.getMessage());
			log.error(e.getMessage());
			throw e;
		}
		return false;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:44:55 PM 
	 * CreateBy=Chatree Siangklom
	 * PermanentReceipt
	 * TODO
	 * @param value
	 * @return
	 * @throws Exception
	 */
	private PermanentReceipt setHeader(FiReReceiptInb value) throws Exception {
		try{
			
			PermanentReceipt model;
			
			model = PermanentReceiptServ.findBySapReceiptedNoWithoutSyag(value.getExtRefNo(), value.getStatus());
			if(model != null){
				System.out.println("Can't Create SAP Receipt No "+ model.getSyncExternalRefNo() +" is duplicated, The current status is Approved.");
				log.error("Can't Create SAP Receipt No "+ model.getSyncExternalRefNo() +" is duplicated, The current status is Approved.");
				throw new Exception("Can't Create SAP Receipt No "+ model.getSyncExternalRefNo() +" is duplicated, The current status is Approved.");
			}
				
				
			model = new PermanentReceipt();
			CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(value.getSapPlantCode());
			
			String series = PermanentReceiptServ.getPromisSeriesNext(costProject.getId().getCompany(), costProject.getId().getProject(), "RX", CommonService.ConvertPmsStagingDateTime(value.getReceiptDate()));
			
			//for sales receipt not send project
			Long receiptNumber = PermanentReceiptServ.getPromisDocumentNoNext(costProject.getId().getCompany(), null, "RX", series);
			System.out.println("New receiptNumber:" + receiptNumber);
			log.info("New receiptNumber:" + receiptNumber);
	
			PermanentReceiptPK id = new PermanentReceiptPK();
			id.setCompany(costProject.getId().getCompany());
			id.setProject(costProject.getId().getProject());
			id.setReceiptType("RX");
			id.setReceiptSeries(series);
			id.setReceiptNumber(receiptNumber);
			model.setId(id);
			
			//Add date : 2012-08-27
			//Boy Confirm : 2012-08-27 
			model.setVoucherType(id.getReceiptType());
			model.setVoucherSeries(id.getReceiptSeries());
			model.setVoucherNumber(CommonService.ConvertStringToBigDecimal(id.getReceiptNumber()+""));			
			model.setProjectRef(costProject.getId().getProject());
			
			model.setReceiptDate(CommonService.ConvertStringToDateTime(value.getReceiptDate()));
			model.setStatus(value.getStatus());
			
			boolean iscanReceipt = false;
			if(!CommonService.IsNull(value.getBookingDocumentNo()))
				{iscanReceipt = isCanReceipt(costProject.getId().getCompany(), costProject.getId().getProject(), CommonService.IsNullRZero(value.getBookingDocumentNo()));}
			
			if(!CommonService.IsNull(value.getContractDocumentNo()))
				{iscanReceipt = isCanReceipt(costProject.getId().getCompany(), costProject.getId().getProject(), CommonService.IsNullRZero(value.getContractDocumentNo()));}
			
			if(iscanReceipt){
				boolean b1 = false;
				boolean b2 = false;
				//Sales Contract
				List<VwSyncMktCustBookCont> lst = new VwSyncMktCustBookContServices(EmPromis).findByDocumentNo(costProject.getId().getCompany(), costProject.getId().getProject() , value.getContractDocumentNo(), null);
				if(!CommonService.IsNull(lst))
				{
					VwSyncMktCustBookCont book_contr = lst.get(0);
					model.setTypeOfContract(book_contr.getDocumentType());
					model.setContractSeries(book_contr.getDocumentSeries());
					model.setContractNumber(new BigDecimal(book_contr.getDocumentNo().toString()));
					model.setRevisionNumber(new BigDecimal(book_contr.getRevisionNumber().toString()));
					
					b1 = true;
				}else
					b1 = false;
				
				//Sales Booking
				lst = new VwSyncMktCustBookContServices(EmPromis).findByDocumentNo(costProject.getId().getCompany(), costProject.getId().getProject() , value.getBookingDocumentNo(), null);
				if(!CommonService.IsNull(lst))
				{
					VwSyncMktCustBookCont book_contr = lst.get(0);
					model.setTypeOfBooking(book_contr.getDocumentType());
					model.setBookingSeries(book_contr.getDocumentSeries());
					model.setBookingNumber(new BigDecimal(book_contr.getDocumentNo().toString()));
					b2 = true;
				}else
					b2 = false;
				
				if(b1 == false && b2 == false){					
					System.out.println("Data not found Sales Booking Or Sales Contract the current status not eq Approved [SAP BS,CS DOC :"+ value.getBookingDocumentNo() + " || " + value.getContractDocumentNo() +"]");
					log.error("Data not found Sales Booking Or Sales Contract the current status not eq Approved [SAP BS,CS DOC :"+ value.getBookingDocumentNo() + " || " + value.getContractDocumentNo() +"]");
					throw new Exception("Data not found Sales Booking Or Sales Contract the current status not eq Approved [SAP BS,CS DOC :"+ value.getBookingDocumentNo() + " || " + value.getContractDocumentNo() +"]");
				}
			}else{
				System.out.println("Data not found Sales Booking Or Sales Contract the current status not eq Approved [SAP BS,CS DOC :"+ value.getBookingDocumentNo() + " || " + value.getContractDocumentNo() +"]");
				log.error("Data not found Sales Booking Or Sales Contract the current status not eq Approved [SAP BS,CS DOC :"+ value.getBookingDocumentNo() + " || " + value.getContractDocumentNo() +"]");
				throw new Exception("Data not found Sales Booking Or Sales Contract the current status not eq Approved [SAP BS,CS DOC :"+ value.getBookingDocumentNo() + " || " + value.getContractDocumentNo() +"]");
			}
			
			if(!CommonService.IsNull(value.getInterestReceived()))
				model.setInterestReceived(new BigDecimal(value.getInterestReceived()));
			
			if(!CommonService.IsNull(value.getDiscount()))
				model.setDiscount(new BigDecimal(value.getDiscount()));
			
			if(!CommonService.IsNull(value.getAmount()))
				model.setAmount(new BigDecimal(value.getAmount()));
			
			if(!CommonService.IsNull(value.getVatAmount()))
				model.setVatAmount(new BigDecimal(value.getVatAmount()));
			
			if(!CommonService.IsNull(value.getWhtAmount()))
				model.setWhtAmount(new BigDecimal(value.getWhtAmount()));
			
			if(!CommonService.IsNull(value.getRemarksH()))
				model.setRemarks(value.getRemarksH());
			
			if(!CommonService.IsNull(value.getPropertyTypeCode()))
				model.setPropertyTypeCode(value.getPropertyTypeCode());
			
			if(value.getPropertyTypeCode().equals("1") || 
					value.getPropertyTypeCode().equals("2") || 
					value.getPropertyTypeCode().equals("3") || 
					value.getPropertyTypeCode().equals("4") || 
					value.getPropertyTypeCode().equals("5") ||
					value.getPropertyTypeCode().equals("6") ||
					value.getPropertyTypeCode().equals("7") ||
					value.getPropertyTypeCode().equals("8") ||
					value.getPropertyTypeCode().equals("9")){
			}else{
				System.out.println("Property Type Code orver scorp [1...9] ");
				log.error("Property Type Code orver scorp [1...9] ");
				throw new Exception("Property Type Code orver scorp [1...9] ");
			}
				
			
			if(!CommonService.IsNull(value.getBuildingPhaseCode()))
				model.setBuildingPhaseCode(value.getBuildingPhaseCode());
			
			if(!CommonService.IsNull(value.getBuildingPhaseCode()))
				model.setDepartmentCode(value.getBuildingPhaseCode());
			
			if(!CommonService.IsNull(value.getFloorZoneCode()))
				model.setFloorZoneCode(value.getFloorZoneCode());
			
			if(!CommonService.IsNull(value.getUnitNumber()))
				model.setUnitNumber(value.getUnitNumber());
			
			if(!CommonService.IsNull(value.getAddressCustomer()))
				model.setAddressCustomer(value.getAddressCustomer());
			
			if(!CommonService.IsNull(value.getNetAmountReceived()))
				model.setNetAmountReceived(new BigDecimal(value.getNetAmountReceived()));
			
			if(!CommonService.IsNull(value.getCustomerCode()))
				model.setCustomerCode(value.getCustomerCode());
			
			if(!CommonService.IsNull(value.getNarration()))
				model.setNarration(value.getNarration());
			
			if(!CommonService.IsNull(value.getReceivedFrom()))
				model.setReceivedFrom(value.getReceivedFrom());
			
			if(!CommonService.IsNull(value.getRefDocument()))
				model.setRefDocument(value.getRefDocument());
			else{
				//Dr.Tree Comment 2012-10-02 use from SAP REF DOC
				//String ref_document = PermanentReceiptServ.MktRunningNon(model.getId().getCompany(), model.getId().getProject(), model.getId().getReceiptType());
				//model.setRefDocument(ref_document);
			}
			
			model.setCurrency("THB");
			model.setCustomerName(value.getCustomerName());
			model.setCustomerNameEng(value.getCustomerCode());
			
			model.setCreatedOn(CommonService.ConvertStringToDateTime(value.getCreatedOn()));
			model.setCreatedBy(value.getCreatedBy());
			model.setLastUpdOn(CommonService.ConvertStringToDateTime(value.getUpdatedOn()));
			model.setLastUpdBy(value.getUpdatedBy());
			
			model.setSyncIsstaging("Y");
			model.setSyncIssync("Y");
			model.setSyncCreatedby(SAPServerInfo.User());
			model.setSyncCreatedon(Calendar.getInstance().getTime());
			model.setSyncUpdatedby(SAPServerInfo.User());
			model.setSyncUpdatedon(Calendar.getInstance().getTime());
			model.setSyncExternalRefKey(value.getExtRefKey());
			model.setSyncExternalRefNo(value.getExtRefNo());
			
			//ADD 2013-03-11
			//DR.TREE
			//FOR Receipt PDC
			model.setChequePdcRef(value.getChequePdcRef());
			
			
			return model;			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:45:10 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param lst
	 * @throws Exception
	 */
	//Per receipt transaction.
	private void Created(List<FiReReceiptInb> lst) throws Exception {		
		System.out.println("Start ReReceiptedAction size=" + CommonService.getSize(lst));
		
		try{
						
			//Check is can receipt
			CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(lst.get(0).getSapPlantCode());
			for(FiReReceiptInb value : lst){
				
				if(!CommonService.IsNull(value.getBookingDocumentNo())){
					if(!CommonService.findString(CommonService.IsNullRString(value.getBookingDocumentNo()), "BS")){
						log.error("Data not found wrong value booking document=" + value.getBookingDocumentNo() + " || REF SAP DOC="+ value.getExtRefNo());
						System.out.println("Data not found wrong value booking document=" + value.getBookingDocumentNo() + " || REF SAP DOC="+ value.getExtRefNo());
						throw new Exception("Data not found wrong value booking document=" + value.getBookingDocumentNo() + " || REF SAP DOC="+ value.getExtRefNo());
					}						
				}
				
				if(!CommonService.IsNull(value.getContractDocumentNo())){
					if(!CommonService.findString(CommonService.IsNullRString(value.getContractDocumentNo()), "CS")){
						System.out.println("Data not found wrong value sales contract document=" + value.getContractDocumentNo() + " || REF SAP DOC="+ value.getExtRefNo());
						log.error("Data not found wrong value sales contract document=" + value.getContractDocumentNo() + " || REF SAP DOC="+ value.getExtRefNo());
						throw new Exception("Data not found wrong value sales contract document=" + value.getContractDocumentNo() + " || REF SAP DOC="+ value.getExtRefNo());
					}
				}
				
				String document_number = value.getBookingDocumentNo(); 
				String CONTRACT_DOCUMENT_NO = value.getContractDocumentNo();
				if(!CommonService.IsNull(CONTRACT_DOCUMENT_NO))
					document_number = CONTRACT_DOCUMENT_NO;
				
				int installment_number = Integer.parseInt(value.getInstallmentNumber());
				int installment_seq = Integer.parseInt(value.getInstallmentSeq());
				
				if(!IsCanReceipt(costProject.getId().getCompany(), costProject.getId().getProject(), document_number, installment_number, installment_seq))
				{
					System.out.println("Can't Create Receipt (INSTALLMENT_AMOUNT_PAID >= INSTALLMENT_DUE_AMOUNT) SAP DOC="+ value.getExtRefNo() +" [plant_code="+ value.getPlantCode() +"||ref document_number="+ document_number +"||installment_number="+ installment_number +"||installment_seq="+ installment_seq +"] ");
					log.error("Can't Create Receipt (INSTALLMENT_AMOUNT_PAID >= INSTALLMENT_DUE_AMOUNT) SAP DOC="+ value.getExtRefNo() +" [plant_code="+ value.getPlantCode() +"||ref document_number="+ document_number +"||installment_number="+ installment_number +"||installment_seq="+ installment_seq +"] ");
					throw new Exception("Can't Create Receipt (INSTALLMENT_AMOUNT_PAID >= INSTALLMENT_DUE_AMOUNT) SAP DOC="+ value.getExtRefNo() +" [plant_code="+ value.getPlantCode() +"||ref document_number="+ document_number +"||installment_number="+ installment_number +"||installment_seq="+ installment_seq +"] ");
				}				
			}
			
			PermanentReceipt permanentReceipt = new PermanentReceipt();
			MktReceiptDetail mktReceiptDetail = new MktReceiptDetail();
			PmsPaymentReceivedDetail pmsPaymentReceivedDetail = new PmsPaymentReceivedDetail();			
			MktPaymentReceiptDetail mktPaymentReceiptDetail = new MktPaymentReceiptDetail();
			
			//Set Header
			permanentReceipt = setHeader(lst.get(0));
			
			for(FiReReceiptInb value : lst)
			{				
				PmsPaymentReceivedDetailPK id = new PmsPaymentReceivedDetailPK();  
				id.setCompany(permanentReceipt.getId().getCompany());					//log.info(" permanentReceipt.getId().getCompany() = " + permanentReceipt.getId().getCompany());
				id.setVoucherType(permanentReceipt.getId().getReceiptType());			//log.info(" permanentReceipt.getId().getReceiptType() = " + permanentReceipt.getId().getReceiptType());
				id.setVoucherSeries(permanentReceipt.getId().getReceiptSeries());		//log.info(" permanentReceipt.getId().getReceiptSeries() = " + permanentReceipt.getId().getReceiptSeries());
				id.setVoucherNo(permanentReceipt.getId().getReceiptNumber());			//log.info(" permanentReceipt.getId().getReceiptNumber() = " + permanentReceipt.getId().getReceiptNumber());
																						//log.info(" Long.parseLong(value.getSeqNo()) = " + Long.parseLong(value.getSeqNo()));
				if(!CommonService.IsNull(value.getSeqNo()))
					id.setSeqNo(Long.parseLong(value.getSeqNo()));						
				
				pmsPaymentReceivedDetail.setId(id);
				
				pmsPaymentReceivedDetail.setProjectRef(permanentReceipt.getProjectRef());				
				pmsPaymentReceivedDetail.setVoucherDate(permanentReceipt.getReceiptDate());
				pmsPaymentReceivedDetail.setReceivedType(value.getReceivedType());
				pmsPaymentReceivedDetail.setCustomerCode(value.getCustomerCode());
				
				//find Customer by Code
				/*
				BusinessPartner customer = new BusinessPartnerServices(EmPromis).findByCustomerNo(value.getCustomerCode());		
				if(customer != null){
					String fullname = "";
					if(!CommonService.IsNull(customer.getBpNameThai()))
						fullname = CommonService.IsNullRString(customer.getTitleThai()) + CommonService.IsNullRString(customer.getBpNameThai()) + " " + CommonService.IsNullRString(customer.getBpLastnameThai());
					else 
						fullname = CommonService.IsNullRString(customer.getTitleEng()) + CommonService.IsNullRString(customer.getBpNameEng()) + " " + CommonService.IsNullRString(customer.getBpLastnameEng());
					
					pmsPaymentReceivedDetail.setPayeeName(fullname);
				}
				*/
				
				pmsPaymentReceivedDetail.setPayeeName(value.getCustomerName());		
				pmsPaymentReceivedDetail.setChequeNumber(value.getChequeNumber());
				pmsPaymentReceivedDetail.setBankCode(value.getBankCode());
				pmsPaymentReceivedDetail.setChequeDueDate(CommonService.ConvertStringToDateTime(value.getChequeDueDate()));				
				
				if(!CommonService.IsNull(value.getChequeAmount()))
					pmsPaymentReceivedDetail.setChequeAmount(new BigDecimal(value.getChequeAmount()));
				
				pmsPaymentReceivedDetail.setRemarks(value.getRemarksD());				
				pmsPaymentReceivedDetail.setChequeIssuingBank(value.getChequeIssuingBank());
				
				if(!CommonService.IsNull(value.getBankCharge()))
					pmsPaymentReceivedDetail.setBankCharge(new BigDecimal(value.getBankCharge()));
				
				pmsPaymentReceivedDetail.setStatus(value.getStatus());
				pmsPaymentReceivedDetail.setProject(costProject.getId().getProject());
				pmsPaymentReceivedDetail.setBankDate(CommonService.ConvertStringToDateTime(value.getBankDate()));
				pmsPaymentReceivedDetail.setPayinDate(CommonService.ConvertStringToDateTime(value.getPayinDate()));
				pmsPaymentReceivedDetail.setBranch(value.getBranch());
				
				if(value.getBankChageRate() != null)
					pmsPaymentReceivedDetail.setBankChargeRate(new BigDecimal(value.getBankChageRate()));
				
				pmsPaymentReceivedDetail.setBankCardReader(value.getBankCardReader());
				pmsPaymentReceivedDetail.setCreditCardType(value.getCreditCardType());
				
				
				pmsPaymentReceivedDetail.setCreatedOn(CommonService.ConvertStringToDateTime(value.getCreatedOn()));
				pmsPaymentReceivedDetail.setCreatedBy(value.getCreatedBy());
				pmsPaymentReceivedDetail.setLastUpdOn(CommonService.ConvertStringToDateTime(value.getUpdatedOn()));
				pmsPaymentReceivedDetail.setLastUpdBy(value.getUpdatedBy());
				
				pmsPaymentReceivedDetail.setSyncIsstaging("Y");
				pmsPaymentReceivedDetail.setSyncIssync("Y");				
				pmsPaymentReceivedDetail.setSyncCreatedby(SAPServerInfo.User());
				pmsPaymentReceivedDetail.setSyncCreatedon(Calendar.getInstance().getTime());
				pmsPaymentReceivedDetail.setSyncUpdatedby(SAPServerInfo.User());
				pmsPaymentReceivedDetail.setSyncUpdatedon(Calendar.getInstance().getTime());
				pmsPaymentReceivedDetail.setSyncExternalRefKey(value.getExtRefKey());
				pmsPaymentReceivedDetail.setSyncExternalRefNo(value.getExtRefNo());
				
				//===========================================================================================
				MktReceiptDetailPK id0 = new MktReceiptDetailPK();
				id0.setCompany(permanentReceipt.getId().getCompany());
				id0.setReceiptType(permanentReceipt.getId().getReceiptType());
				id0.setReceiptNumber(permanentReceipt.getId().getReceiptNumber());
				id0.setReceiptSeries(permanentReceipt.getId().getReceiptSeries());
				//U = Unit , C = Charge Code
				id0.setFlagCharge("U");
				//id0.setUnitNumber(permanentReceipt.getUnitNumber());
				//id0.setPaymentType(value.getPaymentType());
				id0.setSeqNo(Long.parseLong(value.getSeqNo()));
				
				mktReceiptDetail.setId(id0);
				
				mktReceiptDetail.setPaymentType(value.getPaymentType());
				mktReceiptDetail.setUnitNumber(value.getUnitNumber());
				mktReceiptDetail.setProject(costProject.getId().getProject());
				mktReceiptDetail.setReceiptDate(permanentReceipt.getReceiptDate());				
				
				if(!CommonService.IsNull(value.getBookingDocumentNo())){
					mktReceiptDetail.setVoucherType(permanentReceipt.getTypeOfBooking());
					mktReceiptDetail.setVoucherSeries(permanentReceipt.getBookingSeries());
					mktReceiptDetail.setVoucherNumber(permanentReceipt.getBookingNumber());
				}
				
				if(!CommonService.IsNull(value.getContractDocumentNo())){
					mktReceiptDetail.setVoucherType(permanentReceipt.getTypeOfContract());
					mktReceiptDetail.setVoucherSeries(permanentReceipt.getContractSeries());
					mktReceiptDetail.setVoucherNumber(permanentReceipt.getContractNumber());
					mktReceiptDetail.setRevisionNumber(permanentReceipt.getRevisionNumber());
				}				
				
				if(!CommonService.IsNull(value.getInstallmentSeq()))
					mktReceiptDetail.setInstallmentSeq(new BigDecimal(value.getInstallmentSeq()));
				
				/*
				if(!CommonService.IsNull(value.getInstallmentNumber()))
					id0.setInstallmentNumber(Long.parseLong(value.getInstallmentNumber()));
				*/
				
				mktReceiptDetail.setInstallmentNumber(new BigDecimal(value.getInstallmentNumber()));				
				
				if(!CommonService.IsNull(value.getAmountReceived()))
					mktReceiptDetail.setAmountReceived(new BigDecimal(value.getAmountReceived()));
				
				mktReceiptDetail.setStatus(permanentReceipt.getStatus());
				
				if(!CommonService.IsNull(value.getPaymentSeq()))
					mktReceiptDetail.setPaymentSeq(new BigDecimal(value.getPaymentSeq()));
				
				mktReceiptDetail.setPaymentType(value.getPaymentType());
				
				
				mktReceiptDetail.setCreatedOn(CommonService.ConvertStringToDateTime(value.getCreatedOn()));
				mktReceiptDetail.setCreatedBy(value.getCreatedBy());
				mktReceiptDetail.setLastUpdOn(CommonService.ConvertStringToDateTime(value.getUpdatedOn()));
				mktReceiptDetail.setLastUpdBy(value.getUpdatedBy());
				
				mktReceiptDetail.setAmount(CommonService.ConvertStringToBigDecimal(value.getInstallmentDueAmount()));
				
				mktReceiptDetail.setSyncIsstaging("Y");
				mktReceiptDetail.setSyncIssync("Y");
				mktReceiptDetail.setSyncCreatedby(SAPServerInfo.User());
				mktReceiptDetail.setSyncCreatedon(Calendar.getInstance().getTime());
				mktReceiptDetail.setSyncUpdatedby(SAPServerInfo.User());
				mktReceiptDetail.setSyncUpdatedon(Calendar.getInstance().getTime());
				mktReceiptDetail.setSyncExternalRefKey(value.getExtRefKey());
				mktReceiptDetail.setSyncExternalRefNo(value.getExtRefNo());
				
				//==========================================================================
				MktPaymentReceiptDetailPK id1 = new MktPaymentReceiptDetailPK();
				id1.setCompany(permanentReceipt.getId().getCompany());				
				//id1.setInstallmentNumber(mktReceiptDetail.getId().getInstallmentNumber());
				//id1.setInstallmentSeq(Long.parseLong(mktReceiptDetail.getInstallmentSeq().toString()));
				//id1.setPaymentType(mktReceiptDetail.getId().getPaymentType());
				id1.setReceiptNumber(permanentReceipt.getId().getReceiptNumber());
				id1.setReceiptSeries(permanentReceipt.getId().getReceiptSeries());
				id1.setReceiptType(permanentReceipt.getId().getReceiptType());
				//id1.setReceivedType(pmsPaymentReceivedDetail.getReceivedType());
				id1.setUnitNumber(value.getUnitNumber());				
				
				//id1.setSeqNo(Long.parseLong(permanentReceipt.getSeqNo().toString()));
				id1.setSeqNo(Long.parseLong(CommonService.IsNullRZero(value.getSeqNo())));
				
				mktPaymentReceiptDetail.setId(id1);
				
				mktPaymentReceiptDetail.setReceiptDate(mktReceiptDetail.getReceiptDate());
				mktPaymentReceiptDetail.setProject(mktReceiptDetail.getProject());
				mktPaymentReceiptDetail.setVoucherType(permanentReceipt.getVoucherType());
				mktPaymentReceiptDetail.setVoucherSeries(permanentReceipt.getVoucherSeries());
				mktPaymentReceiptDetail.setVoucherNumber(permanentReceipt.getVoucherNumber());				
				mktPaymentReceiptDetail.setAmountReceived(mktReceiptDetail.getAmountReceived());
				mktPaymentReceiptDetail.setChequeNumber(pmsPaymentReceivedDetail.getChequeNumber());
				mktPaymentReceiptDetail.setChequeDueDate(pmsPaymentReceivedDetail.getChequeDueDate());
				mktPaymentReceiptDetail.setChequeIssuingBank(pmsPaymentReceivedDetail.getChequeIssuingBank());
				mktPaymentReceiptDetail.setBankCardReader(pmsPaymentReceivedDetail.getBankCardReader());
				mktPaymentReceiptDetail.setCreditCardType(pmsPaymentReceivedDetail.getCreditCardType());
				mktPaymentReceiptDetail.setChequeAmount(pmsPaymentReceivedDetail.getChequeAmount());
				mktPaymentReceiptDetail.setBankRate(pmsPaymentReceivedDetail.getBankRate());
				mktPaymentReceiptDetail.setBankCharge(pmsPaymentReceivedDetail.getBankCharge());
				mktPaymentReceiptDetail.setTypeOfContract(permanentReceipt.getTypeOfContract());
				mktPaymentReceiptDetail.setContractSeries(permanentReceipt.getContractSeries());
				mktPaymentReceiptDetail.setContractNo(permanentReceipt.getContractNumber());				
				mktPaymentReceiptDetail.setRevisionNumber(permanentReceipt.getRevisionNumber());
				
				mktPaymentReceiptDetail.setPaymentType(value.getPaymentType());
				mktPaymentReceiptDetail.setFlagCharge("U");
				mktPaymentReceiptDetail.setInstallmentSeq(CommonService.ConvertStringToBigDecimal(value.getInstallmentSeq()));
				mktPaymentReceiptDetail.setInstallmentNumber(CommonService.ConvertStringToBigDecimal(value.getInstallmentNumber()));
				mktPaymentReceiptDetail.setReceivedType(value.getReceivedType());
				mktPaymentReceiptDetail.setSyncIsstaging("Y");
				mktPaymentReceiptDetail.setSyncIssync("Y");
				
				mktPaymentReceiptDetail.setSyncCreatedby(SAPServerInfo.User());
				mktPaymentReceiptDetail.setSyncCreatedon(Calendar.getInstance().getTime());
				mktPaymentReceiptDetail.setSyncUpdatedby(SAPServerInfo.User());
				mktPaymentReceiptDetail.setSyncUpdatedon(Calendar.getInstance().getTime());
				mktPaymentReceiptDetail.setSyncExternalRefKey(value.getExtRefKey());
				mktPaymentReceiptDetail.setSyncExternalRefNo(value.getExtRefNo());
			}
			
			EntityTransaction t = null;
			try{			
		        t = EmPromis.getTransaction();
		        t.begin();
		        
			        EmPromis.persist(permanentReceipt);
			        EmPromis.persist(mktReceiptDetail);
			        EmPromis.persist(pmsPaymentReceivedDetail);
			        EmPromis.persist(mktPaymentReceiptDetail);
			        
		        t.commit();
		        EmPromis.flush();
		        
			}catch(Exception e){
				e.printStackTrace();
				log.error(e.getMessage());
			}finally{
				if (t.isActive()) 
					t.rollback();
			}
			
			if(!CommonService.IsNull(lst)){
				List<FiReReceiptInb> lstnew = new ArrayList<FiReReceiptInb>();
				
				StringBuilder doc = new StringBuilder();
				doc.append(permanentReceipt.getId().getReceiptType()).append("-");
				doc.append(permanentReceipt.getId().getReceiptSeries()).append("-");
				doc.append(Utilitys.leftPad(CommonService.IsNullRString(permanentReceipt.getId().getReceiptNumber()), 6, "0"));
				
				for(FiReReceiptInb model : lst){
					model.setPmsReReceiptNo(doc.toString());
					model.setIssync("Y");
					model.setMsgCode("S");
					model.setMsgDesc("Success");
					model.setMsgAltDesc("ExtRefNo:" + model.getExtRefNo() + "||ExtRefKey:" + model.getExtRefKey());
					lstnew.add(model);
				}
				
				//Update Success
				new FiReReceiptInbservices(EmSynchro).Updated(lstnew);
			}
			
		}catch(Exception e)
		{
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}finally{
			log.info("End of ReReceiptedAction size=" + CommonService.getSize(lst));
		}
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:46:35 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param lst
	 * @throws Exception
	 */
	private void Canceled(List<FiReReceiptInb> lst) throws Exception 
	{
		log.info("ReReceiptedAction Canceled...");
		if(!CommonService.IsNull(lst)){
			try{
				
				FiReReceiptInb value = lst.get(0);
				
				PermanentReceipt model = PermanentReceiptServ.findBySapReceiptedNoWithoutSyag(value.getExtRefNo(), "A");
				if(model != null)
				{
					if(CommonService.IsNullRString(value.getStatus()).toUpperCase().equals("Z") && CommonService.IsNullRString(model.getStatus()).toUpperCase().equals("A")) {
						model.setStatus("Z");
						PermanentReceiptServ.Updated(model);
					}else
					{
						System.out.println("SAP Receipt No : "+ model.getSyncExternalRefNo() +" Can't Cancel the current status is equals Cancel.");
						log.error("SAP Receipt No : "+ model.getSyncExternalRefNo() +" Can't Cancel the current status is equals Cancel.");
						throw new Exception("SAP Receipt No : "+ model.getSyncExternalRefNo() +" Can't Cancel the current status is equals Cancel.");	
					}
						
				}else{
					System.out.println("Data not found Receipt document [SAP Receipt No:"+ value.getExtRefNo() +"]");
					log.error("Data not found Receipt document [SAP Receipt No:"+ value.getExtRefNo() +"]");
					throw new Exception("Data not found Receipt document [SAP Receipt No:"+ value.getExtRefNo() +"]");
				}
				
				if(!CommonService.IsNull(lst)){
					List<FiReReceiptInb> lstnew = new ArrayList<FiReReceiptInb>();
					StringBuilder doc = new StringBuilder();
					doc.append(model.getId().getReceiptType()).append("-");
					doc.append(model.getId().getReceiptSeries()).append("-");
					doc.append(Utilitys.leftPad(CommonService.IsNullRString(model.getId().getReceiptNumber()), 6, "0"));
					
					for(FiReReceiptInb obj : lst){
						obj.setPmsReReceiptNo(doc.toString());
						obj.setIssync("Y");
						obj.setMsgCode("S");
						obj.setMsgDesc("Success");
						obj.setMsgAltDesc("ExtRefNo:" + obj.getExtRefNo() + "||ExtRefKey:" + obj.getExtRefKey());
						lstnew.add(obj);
					}
					
					//Update Success
					new FiReReceiptInbservices(EmSynchro).Updated(lstnew);
				}
				
			}catch(Exception e)
			{
				System.out.println(e.getMessage());
				log.error(e.getMessage());
				if(CommonService.getSize(lst) > 0){
					
					List<FiReReceiptInb> lstnew = new ArrayList<FiReReceiptInb>();
					for(FiReReceiptInb obj : lst){
						obj.setIssync("N");
						obj.setMsgCode("E");
						obj.setMsgDesc(CommonService.CutString(e.getMessage(), 3500));
						obj.setMsgAltDesc("ExtRefNo:" + obj.getExtRefNo() + "||ExtRefKey:" + obj.getExtRefKey());
						lstnew.add(obj);
					}
					
					//Update Success
					new FiReReceiptInbservices(EmSynchro).Updated(lstnew);
				}
				
				log.error(e.getMessage());
				System.err.println(e.getMessage());
				throw e;
			}	
		}
	}
	
	/**
	 * COMPANY, PROJECT, DOCUMENT_NUMBER, INSTALLMENT_DUE_AMOUNT,INSTALLMENT_AMOUNT_PAID, INSTALLMENT_DUE_DATE, PAYMENT_TYPE, PAYMENT_TYPE_DESC
	 * @param company
	 * @param project
	 * @param document_number
	 * @param installment_number
	 * @param installment_seq
	 * @return
	 * @throws Exception
	 */
	private boolean IsCanReceipt(String company, String project, String document_number, int installment_number, int installment_seq) throws Exception {
		try{
			StringBuilder _strQuery = new StringBuilder();
			_strQuery.append(" SELECT ");
			_strQuery.append(" COMPANY, PROJECT, DOCUMENT_NUMBER, NVL(INSTALLMENT_DUE_AMOUNT,0) AS INSTALLMENT_DUE_AMOUNT , NVL(INSTALLMENT_AMOUNT_PAID,0) AS INSTALLMENT_AMOUNT_PAID , INSTALLMENT_DUE_DATE, PAYMENT_TYPE, PAYMENT_TYPE_DESC "); 
			_strQuery.append(" FROM SPL.VW_SYNC_MKT_CUST_BOOK_CONT ");
			_strQuery.append(" WHERE ");
			_strQuery.append("     COMPANY = ").append(Utilitys.strSql(company));
			_strQuery.append(" AND PROJECT = ").append(Utilitys.strSql(project));
			_strQuery.append(" AND DOCUMENT_NUMBER   = ").append(Utilitys.strSql(document_number));
			_strQuery.append(" AND INSTALLMENT_NUMBER = ").append(installment_number);
			_strQuery.append(" AND INSTALLMENT_SEQ = ").append(installment_seq);
			_strQuery.append(" ORDER BY INSTALLMENT_SEQ ");
			
			List<Object[]> result = (List<Object[]>)EmPromis.createNativeQuery(_strQuery.toString()).getResultList();
			if(CommonService.getSize(result) == 1){
				for (Object[] value : result) {
					
					double INSTALLMENT_DUE_AMOUNT = CommonService.ConvertStringToLong(value[3]);
					double INSTALLMENT_AMOUNT_PAID = CommonService.ConvertStringToLong(value[4]);
					
					return (INSTALLMENT_AMOUNT_PAID >= INSTALLMENT_DUE_AMOUNT) ? false : true;
				}
			}else
				return false;
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.out.println(e.getMessage());
			throw e;
		}
		return false;
	}
	
	/**
	 * Per Receipt document 
	 * @param obj_lst
	 * @throws Exception
	 */
	public void Processing(List<FiReReceiptInb> lst) throws Exception {
		
		try{
			PermanentReceiptServ = new PermanentReceiptServices(EmPromis);
			FiReReceiptInbserv = new FiReReceiptInbservices(EmSynchro);
			
			if(!CommonService.IsNull(lst)){
				
				String status = lst.get(0).getStatus();
				
				if(CommonService.IsNullRString(status).toUpperCase().equals("Z")){
					//Cancel receipted
					Canceled(lst);
				}else if(CommonService.IsNullRString(status).toUpperCase().equals("A")){
					//Create receipted
					Created(lst);
				}
			}
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}

	/**
	 * 
	 * Date =Nov 13, 2013 : 2:46:42 PM 
	 * CreateBy=Chatree Siangklom
	 * boolean
	 * TODO
	 * @param vlauelist
	 * @return
	 * @throws Exception
	 */
	public boolean ValidatedAndSave(List<FiReReceiptInb> vlauelist) throws Exception {
		log.info("Start ValidatedAndSave size=" + CommonService.getSize(vlauelist));
		
		List<FiReReceiptInb> lst = null;
		boolean ispass = false;
		try{					
			String msg_code = null;
			String msg_desc = null;
			String message = Validate(vlauelist);
			
			log.info("CheckedValidattion message=" + message);
			if(CommonService.IsNull(message)){
				msg_code = "VS";
				msg_desc = "Validate Success";
				ispass = true;
			}else{
				msg_code = "E";
				msg_desc = "Error";
				ispass = false;
			}
			
			lst = new ArrayList<FiReReceiptInb>();
			if(!CommonService.IsNull(vlauelist)){
				for(FiReReceiptInb model : vlauelist)
				{
					Company companySrv = new CompanyServices(EmPromis).findBySapCompany(model.getSapCompanyCode());
					if(!CommonService.IsNull(companySrv)){
						model.setCompanyCode(companySrv.getCompany());
					}
					
					CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(model.getSapPlantCode());
					if(!CommonService.IsNull(costProject)){
						model.setProject(costProject.getId().getProject());
					}
					
					model.setIssync("Y");
					model.setMsgCode(msg_code);					
					model.setMsgDesc(message);
					model.setMsgActResult(message);
					if(!CommonService.IsNull(model.getExtRefKey()))
						model.setMsgAltDesc("SAP Receipt No:" + CommonService.IsNullRString(model.getExtRefNo()) + "//" + "SAP Staging Id = " + CommonService.IsNullRString(model.getExtRefKey()));
					
					lst.add(model);
				}
				
				//Updated
				new FiReReceiptInbservices(EmSynchro).Updated(lst);
			}			
		}catch(Exception e){
			lst = new ArrayList<FiReReceiptInb>();
			if(!CommonService.IsNull(vlauelist)){
				for(FiReReceiptInb model : vlauelist)
				{
					Company companySrv = new CompanyServices(EmPromis).findBySapCompany(model.getSapCompanyCode());
					if(companySrv == null){
						model.setCompanyCode(companySrv.getCompany());
					}
					
					CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(model.getSapPlantCode());
					if(CommonService.IsNull(costProject)){
						model.setProject(costProject.getId().getCompany());
					}
					
					model.setIssync("Y");
					model.setMsgCode("E");									
					model.setMsgDesc(CommonService.CutString(e.getMessage(), 3500));
					if(!CommonService.IsNull(model.getExtRefKey()))
						model.setMsgAltDesc("SAP Receipt No:" + CommonService.IsNullRString(model.getExtRefNo()) + "//" + "SAP Staging Id = " + CommonService.IsNullRString(model.getExtRefKey()));
					
					lst.add(model);
				}
				
				//Updated
				new FiReReceiptInbservices(EmSynchro).Updated(lst);
			}	
			
			log.error(e);
			throw e;
		}finally{
			log.info("End of ValidatedAndSave size=" + CommonService.getSize(vlauelist));
		}
		
		return ispass;
	}

	/**
	 * 
	 * Date =Nov 13, 2013 : 2:47:00 PM 
	 * CreateBy=Chatree Siangklom
	 * String
	 * TODO {Function Validate }
	 * @param vlauelist
	 * @return
	 * @throws Exception
	 */
	private String Validate(List<FiReReceiptInb> vlauelist) throws Exception {
		log.info("Start Validate --->");
		
		String error = null;
		String company = null;
		String project = null;
		String buildingPhase = null;
		String zoneCode = null;
		String unit_number = null;
		int recType = -1;
		
		try{
			
			if(!CommonService.IsNull(vlauelist)){
				for(FiReReceiptInb model : vlauelist)
				{
					/*
					if(CommonService.IsNull(model.getBankChageRate()))
						throw new Exception("field : BANK_CHARGE_RATE is require");
					 */
					
					//Set Txn Reacord					
					if(CommonService.IsNull(model.getCreatedOn())){
						error = "Require field CREATED_ON is require";
						break;
					}
					
					if(CommonService.IsNull(model.getCreatedBy()))
					{
						error = "Require field CREATED_BY is require";
						break;
					}		
					
					/*
					if(CommonService.IsNull(model.getUpdatedOn()))
						throw new Exception("field : LAST_UPD_ON is require");
					*/
					/*
					if(CommonService.IsNull(model.getUpdatedBy()))
						throw new Exception("field : LAST_UPD_BY is require");
					*/
					
					//Set SAP External Key link
					if(CommonService.IsNull(model.getExtRefKey())){
						error = "Require field SYNC_EXTERNAL_REF_KEY is require";
						break;
					}
						
					
					if(CommonService.IsNull(model.getExtRefNo())){
						error = "Require field SYNC_EXTERNAL_REF_NO is require";
						break;
					}
					
					if(CommonService.IsNull(model.getRefDocument())){
						error = "Require field Ref Document is require";
						break;
					}
					
					if(CommonService.IsNull(model.getSapCompanyCode())){					
						error = "Require field SAP Company Code !!!";
						break;
					}
					else
					{
						Company companySrv = new CompanyServices(EmPromis).findBySapCompany(model.getSapCompanyCode());
						if(companySrv == null){
							error = "Data not found SAP Company [" + model.getCompanyCode()+"]";
							break;
						}else
							company = companySrv.getCompany();
					}
					
					//Plant validate **********************************
					if(CommonService.IsNull(model.getSapPlantCode())){
						error = "Require field plant !!!";
						break;
					}
					else
					{
						CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(model.getSapPlantCode());
						if(CommonService.IsNull(costProject)){
							error = "Data not found CostProject SAP plant [" + model.getSapPlantCode()+"]";
							break;
						}else
							project = costProject.getId().getProject();
					}				
					
					if(CommonService.IsNull(model.getReceiptDate())){
						error = "Require field RECEIPT_DATE is require";
						break;
					}
					
					if(CommonService.IsNull(model.getStatus())){
						error = "Require field STATUS is require";
						break;
					}else if(model.getStatus().equals("A")){
						//Approve
					}else if(model.getStatus().equals("Z")){
						//Cancel
					}else
					{
						error = "Data not found STATUS [SAP Status:"+ model.getStatus() +"]";
						break;
					}
					
					if(CommonService.IsNull(model.getContractDocumentNo()) && CommonService.IsNull(model.getBookingDocumentNo())){
						error = "Require field CONTRACT_DOCUMENT_NO or BOOKING_DOCUMENT_NO is require";
						break;
					}else
					{
						
					}
					
					if(CommonService.IsNull(model.getInterestReceived())){
						error = "Require field INTEREST_RECEIVED is require";
						break;
					}
					
					if(CommonService.IsNull(model.getDiscount())){
						error = "Require field DISCOUNT is require";
						break;
					}
					
					if(CommonService.IsNull(model.getCustomerCode())){
						error = "Require field CUSTOMER_CODE is require";
						break;
					}else{
						BusinessPartnerServices BusinessPartnerServ = new BusinessPartnerServices(EmPromis);
						BusinessPartner customerObj = BusinessPartnerServ.findByCustomerNo(model.getCustomerCode());
						if(customerObj == null){
							error = "Data not found Customer [SAP CustomerCode:"+ model.getCustomerCode() +"]";
							break;
						}
					}
					
					/*
					if(CommonService.IsNull(model.getCustomerName()))
						throw new Exception("field : CUSTOMER_NAME is require");
					*/
					
					if(CommonService.IsNull(model.getAmount())){
						error = "Require field AMOUNT is require";
						break;
					}else{
						try{
							
							if(Double.parseDouble(model.getAmount()) <= 0)
							{
								error = "Data not found field AMOUNT <= 0 ";
								break;
							}
							
						}catch(Exception e){
							throw e;
						}
					}
						
					/*
					if(CommonService.IsNull(model.getVatAmount()))
						throw new Exception("field : VAT_AMOUNT is require");
					*/					
					
					CostBuildingPhase CostBuildingPhaseObj = null;
					if(CommonService.IsNull(model.getBuildingPhaseCode())){
						error = "Require field BUILDING_PHASE_CODE is require";
						break;
					}else{
						CostBuildingPhaseServices CostBuildingPhaseServ = new CostBuildingPhaseServices(EmPromis);
						CostBuildingPhasePK id = new CostBuildingPhasePK();
						id.setCompany(company);
						id.setProject(project);
						id.setBuildingPhase(model.getBuildingPhaseCode());
						CostBuildingPhaseObj = CostBuildingPhaseServ.FindByKey(id);
						if(CostBuildingPhaseObj == null){
							error = "Data not found CostBuildingPhase [Company="+ company +" || Project="+ project + " || SAP BuildingPhase=" + model.getBuildingPhaseCode() + "]";
							break;
						}else
							buildingPhase = CostBuildingPhaseObj.getId().getBuildingPhase();
					}
					
					if(CommonService.IsNull(model.getPropertyTypeCode())){
						error = "Require field PROPERTY_TYPE_CODE is require";
						break;
					}
					else
					{
						if(CostBuildingPhaseObj != null){
							if(!CostBuildingPhaseObj.getPropertyTypeCode().equals(model.getPropertyTypeCode())){
								error = "Data not found PropertyTypeCode [SAP:"+ model.getPropertyTypeCode() +" || PMS:"+ CostBuildingPhaseObj.getPropertyTypeCode() +"] !!!";
								break;
							}
						}
					}

					//Floor Zone for Low Rish validate ************************
					if(CommonService.IsNull(model.getFloorZoneCode())){
						error = "Require field FLOOR_ZONE_CODE is require !!!";
						break;
					}else{
						CostProjectZoneServices CostProjectZoneServ = new CostProjectZoneServices(EmPromis);
						CostProjectZonePK id = new CostProjectZonePK();
						id.setCompany(company);
						id.setProject(project);
						id.setBuildingPhase(buildingPhase);
						id.setZoneCode(model.getFloorZoneCode());
						
						CostProjectZone CostProjectZoneObj = CostProjectZoneServ.FindByKey(id);
						if(CostProjectZoneObj == null){
							error = "Data not found CostProjectZone [Company="+ company +" || Project="+ project + " ||BuildingPhase=" + model.getBuildingPhaseCode() + " || SAP FloorZoneCode="+ model.getFloorZoneCode() +" ]";
							break;
						}else
							zoneCode = CostProjectZoneObj.getId().getZoneCode();
					}
					
					//Unit Number validate  ****************************
					if(CommonService.IsNull(model.getUnitNumber())){					
						error = "Require field UNIT_NUMBER !!!";
						break;
					}else
					{
						CostProjectUnitServices CostProjectUnitServ = new CostProjectUnitServices(EmPromis);
						CostProjectUnitPK id = new CostProjectUnitPK();
						id.setCompany(company);
						id.setProject(project);
						id.setBuildingPhase(buildingPhase);					
						id.setZoneCode(zoneCode);
						id.setUnitNumber(model.getUnitNumber());
						CostProjectUnit unitObj = CostProjectUnitServ.findById(id);
						if(unitObj == null){
							error = "Data not found Property Unit [company="+company+"||project="+project+"||buildingPhase="+buildingPhase+"||zoneCode="+zoneCode+"||SAP UnitNumber="+model.getUnitNumber()+"] ";
							break;
						}else
							unit_number = unitObj.getId().getUnitNumber();
					}
					
					if(CommonService.IsNull(model.getPaymentType())){
						error = "Require field PAYMENT_TYPE is require";
						break;
					}else{
						int paymentType = Integer.parseInt(CommonService.IsNullRZero(model.getPaymentType()));
						if(paymentType == 1){
							//Booking
						}else if(paymentType == 2){
							//Contract
						}else if(paymentType == 3){
							//Down
						}else if(paymentType == 4){
							//Transfer
						}else if(paymentType == 5){
							//Additional from Construction (VC)
						}else if(paymentType == 6){
							//Detional from Construction (VC)
						}else{
							error = "Data not found paymentType [SAP paymentType:"+ model.getPaymentType() +"]";
							break;
						}
					}
					
					if(CommonService.IsNull(model.getAddressCustomer())){
						error = "Require field ADDRESS_CUSTOMER is require";
						break;
					}
						
					
					if(CommonService.IsNull(model.getNetAmountReceived())){
						error = "Require field NET_AMOUNT_RECEIVED is require";
						break;
					}
																
					/*
					if(CommonService.IsNull(model.getReceivedFrom()))
						throw new Exception("field : RECEIVED_FROM is require");			
					*/
					
					if(CommonService.IsNull(model.getSeqNo())){
						error = "Require field SEQ_NO is require";
						break;
					}
						
					
					if(Long.parseLong(CommonService.IsNullRZero(model.getSeqNo())) <= 0){
						error = "Require field SEQ_NO < 0, SEQ_NO start at 1....N [SAP SEQNO:"+ model.getSeqNo() +"]";
						break;
					}
						
					
					if(CommonService.IsNull(model.getReceivedType())){
						error = "Require field RECEIVED_TYPE is require";
						break;
					}else{
						recType = Integer.parseInt(CommonService.IsNullRZero(model.getReceivedType()));
						if(recType == 1){
							//CASH
							if(CommonService.IsNull(model.getBranch())){
								error = "Require field BRANCH is require";
								break;
							}
							
						}else if(recType == 2){
							//CHEQUE
							if(CommonService.IsNull(model.getChequeNumber())){
								error = "Require field CHEQUE_NUMBER is require";
								break;
							}else if(CommonService.IsNull(model.getChequeDueDate())){
								error = "Require field CHEQUE_DUE_DATE is require";
								break;
							}else if(CommonService.IsNull(model.getBranch())){
								error = "Require field BRANCH is require";
								break;
							}else if(CommonService.IsNull(model.getChequeIssuingBank())){
								error = "Require field CHEQUE_ISSUING_BANK is require";
								break;
							}
							
						}else if(recType == 3){
							//CREDIT CARD
							if(CommonService.IsNull(model.getCreditCardType())){
								error = "Require field CREDIT_CARD_TYPE is require";
								break;
							}else if(CommonService.IsNull(model.getChequeNumber())){
								error = "Require field CHEQUE_NUMBER is require";
								break;
							}else if(CommonService.IsNull(model.getBankCharge())){
								error = "Require field BANK_CHARGE is require";
								break;
							}else if(CommonService.IsNull(model.getBankCardReader())){
								error = "Require field BANK_CARD_READER is require";
								break;
							}else if(CommonService.IsNull(model.getChequeIssuingBank())){
								error = "Require field CHEQUE_ISSUING_BANK is require";
								break;
							}
							
						}else if(recType == 4){
							//do not adding code
							//TRANSFER
						}else if(recType == 5){
							//PDC
							if(CommonService.IsNull(model.getChequeNumber())){
								error = "Require field CHEQUE_NUMBER is require";
								break;
							}else if(CommonService.IsNull(model.getChequeDueDate())){
								error = "Require field CHEQUE_DUE_DATE is require";
								break;
							}else if(CommonService.IsNull(model.getBranch())){
								error = "Require field BRANCH is require";
								break;
							}else if(CommonService.IsNull(model.getChequeIssuingBank())){
								error = "Require field CHEQUE_ISSUING_BANK is require";
								break;
							}
							
						}else if(recType == 6){
							//CN
						}else if(recType == 7){
							//Bill Payment
							if(CommonService.IsNull(model.getChequeNumber())){
								error = "Require field CHEQUE_NUMBER is require";
								break;
							}
						}else if(recType == 8){
							//Direct Debit
							if(CommonService.IsNull(model.getChequeNumber())){
								error = "Require field CHEQUE_NUMBER is require";
								break;
							}
							
						}else if(recType == 9){
							//Recurring
							if(CommonService.IsNull(model.getChequeNumber())){
								error = "Require field CHEQUE_NUMBER is require";
								break;
							}
						}else if(recType == 10){
							//do not adding code
							//Advance Receipt
						}
						else
						{
							error = "Data not found ReceivedType [SAP:"+ model.getReceivedType() +"] ";
							break;
						}
					}
										
					/*
					if(CommonService.IsNull(model.getBankCode()))
						throw new Exception("field : BANK_CODE is require");
					*/
					
					/*
					if(CommonService.IsNull(model.getChequeAmount()))
						throw new Exception("field : CHEQUE_AMOUNT is require");
					*/
					/*
					if(CommonService.IsNull(model.getRemarksD()))
						throw new Exception("field : REMARKS is require");
					*/					
					
					/*
					if(CommonService.IsNull(model.getBankDate()))
						throw new Exception("field : BANK_DATE is require");
					 */
					/*
					if(CommonService.IsNull(model.getPayinDate()))
						throw new Exception("field : PAYIN_DATE is require");
					*/
						
					
					if(CommonService.IsNull(model.getInstallmentNumber())){
						error = "Require field INSTALLMENT_NUMBER is require";
						break;
					}
					
					if(CommonService.IsNull(model.getInstallmentDueAmount())){
						error = "Require field INSTALLMENT_DUE_AMOUNT is require";
						break;
					}
						
					
					if(CommonService.IsNull(model.getInstallmentSeq())){
						error = "Require field INSTALLMENT_SEQ is require";
						break;
					}
						
					
					if(CommonService.IsNull(model.getAmountReceived())){
						error = "Require field AMOUNT_RECEIVED is require";
						break;
					}
						
					
					if(CommonService.IsNull(model.getPaymentSeq())){
						error = "Require field PAYMENT_SEQ is require";
						break;
					}
					
					if(!CommonService.IsNull(model.getBookingDocumentNo())){
						if(!CommonService.findString(CommonService.IsNullRString(model.getBookingDocumentNo()), "BS")){
							log.error("Data not found wrong value booking document=" + model.getBookingDocumentNo() + " || REF SAP DOC="+ model.getExtRefNo());
							System.out.println("Data not found wrong value booking document=" + model.getBookingDocumentNo() + " || REF SAP DOC="+ model.getExtRefNo());
							error = ("Data not found wrong value booking document=" + model.getBookingDocumentNo() + " || REF SAP DOC="+ model.getExtRefNo());
						}						
					}
					
					if(!CommonService.IsNull(model.getContractDocumentNo())){
						if(!CommonService.findString(CommonService.IsNullRString(model.getContractDocumentNo()), "CS")){
							System.out.println("Data not found wrong value sales contract document=" + model.getContractDocumentNo() + " || REF SAP DOC="+ model.getExtRefNo());
							log.error("Data not found wrong value sales contract document=" + model.getContractDocumentNo() + " || REF SAP DOC="+ model.getExtRefNo());
							error = ("Data not found wrong value sales contract document=" + model.getContractDocumentNo() + " || REF SAP DOC="+ model.getExtRefNo());
						}
					}
					
					String document_number = model.getBookingDocumentNo(); 
					String CONTRACT_DOCUMENT_NO = model.getContractDocumentNo();
					if(!CommonService.IsNull(CONTRACT_DOCUMENT_NO))
						document_number = CONTRACT_DOCUMENT_NO;
					
					int installment_number = Integer.parseInt(model.getInstallmentNumber());
					int installment_seq = Integer.parseInt(model.getInstallmentSeq());
					
					if(model.getStatus().equals("A")){
						if(!IsCanReceipt(company, project, document_number, installment_number, installment_seq))
						{
							System.out.println("Can't Create Receipt (INSTALLMENT_AMOUNT_PAID >= INSTALLMENT_DUE_AMOUNT) SAP DOC="+ model.getExtRefNo() +" [plant_code="+ model.getPlantCode() +"||ref document_number="+ document_number +"||installment_number="+ installment_number +"||installment_seq="+ installment_seq +"] ");
							log.error("Can't Create Receipt (INSTALLMENT_AMOUNT_PAID >= INSTALLMENT_DUE_AMOUNT) SAP DOC="+ model.getExtRefNo() +" [plant_code="+ model.getPlantCode() +"||ref document_number="+ document_number +"||installment_number="+ installment_number +"||installment_seq="+ installment_seq +"] ");
							error = ("Can't Create Receipt (INSTALLMENT_AMOUNT_PAID >= INSTALLMENT_DUE_AMOUNT) SAP DOC="+ model.getExtRefNo() +" [plant_code="+ model.getPlantCode() +"||ref document_number="+ document_number +"||installment_number="+ installment_number +"||installment_seq="+ installment_seq +"] ");
						}	
					}					
					
				}
			}
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}finally{
			log.info("End of Validate [error:"+ error +"] --->");
		}
		return error;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:47:22 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @throws Exception
	 */
	private void Start() throws Exception {
		String sap_receipted_doc_no = "1000-2500011112-2012";
		PermanentReceiptServ = new PermanentReceiptServices(EmPromis);
		FiReReceiptInbserv = new FiReReceiptInbservices(EmSynchro);
		
		try{
			List<ReReceiptedGroupSearch>  receipt_group_lst = groupby(sap_receipted_doc_no);
			for(ReReceiptedGroupSearch value : receipt_group_lst)
			{
				List<FiReReceiptInb> obj_lst = FiReReceiptInbserv.findSapPoDoc(value.getExtRefNo(), value.getStatus(), value.getInstanceNo(), "N");
				if(CommonService.IsNullRString(value.getStatus()).equals("Z")){
					boolean ispass = new ReReceiptedAction().ValidatedAndSave(obj_lst);
					if(ispass){
						//Cancel To Promis
						Canceled(obj_lst);
					}
				}else if(CommonService.IsNullRString(value.getStatus()).equals("A")){
					//Validate Field
					boolean ispass = new ReReceiptedAction().ValidatedAndSave(obj_lst);
					if(ispass){
						//Create To Promis
						Created(obj_lst);
					}
				}
			}
		}catch(Exception e)
		{
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:47:25 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 */
	private void updatePlantCodeProj() {
		try{
			FiReReceiptInbserv = new FiReReceiptInbservices(EmSynchro);
			
			List<FiReReceiptInb>  lst = FiReReceiptInbserv.findAll();
			log.info("lst size="+ CommonService.getSize(lst));
			
			List<FiReReceiptInb> newLst = new ArrayList<FiReReceiptInb>();
			int i = 0;
			for(FiReReceiptInb model : lst)
			{	i++;
				Company companySrv = new CompanyServices(EmPromis).findBySapCompany(model.getSapCompanyCode());
				if(!CommonService.IsNull(companySrv)){
					model.setCompanyCode(companySrv.getCompany());					
				}
				
				CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(model.getSapPlantCode());
				if(!CommonService.IsNull(costProject)){
					model.setProject(costProject.getId().getProject());
				}
				log.info(i + ".Company:"+ model.getCompanyCode() + " || Project:"+ model.getProject());
				
				FiReReceiptInbserv.Updated(model);
			}
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
//	
//	public static void main(String[] args) {
//		// TODO Auto-generated method stub
//		try{
//			
//			ReReceiptedAction obj = new ReReceiptedAction();
//			obj.Start();
//			
//		}catch(Exception e)
//		{
//			log.error(e.getMessage());
//			System.err.println(e.getMessage());
//		}
//	}
}